﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using dreamwork.web.mvc.app.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using IdentityModel.Client;
using System.Net.Http;
using Newtonsoft.Json.Linq;

namespace dreamwork.web.mvc.app.Controllers
{
	public class HomeController : Controller
	{

		public IActionResult Index()
		{
			return View();
		}

		[Authorize]
		public IActionResult Secure()
		{
			ViewData["Message"] = "Secure page.";

			return View();
		}

		public async Task Logout()
		{
			await HttpContext.SignOutAsync("Cookies");
			await HttpContext.SignOutAsync("oidc");
		}

		public async Task<IActionResult> CallApiUsingClientCredentials()
		{
			var tokenClient = new TokenClient("http://localhost:5200/connect/token", "dreamwork.web.mvc.app", "secret");
			var tokenResponse = await tokenClient.RequestClientCredentialsAsync("dreamwork.exam.api");

			var client = new HttpClient();
			client.SetBearerToken(tokenResponse.AccessToken);
			var content = await client.GetStringAsync("http://localhost:5208/api/identity/get");

			ViewBag.Json = JArray.Parse(content).ToString();
			return View("Json");
		}

		public async Task<IActionResult> CallApiUsingUserAccessToken()
		{
			var accessToken = await HttpContext.GetTokenAsync("access_token");

			var client = new HttpClient();
			client.SetBearerToken(accessToken);
			var content = await client.GetStringAsync("http://localhost:5208/api/identity/get");

			ViewBag.Json = JArray.Parse(content).ToString();
			return View("Json");
		}

		[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
		public IActionResult Error()
		{
			return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
		}
	}
}
